package com.xxx.service;

import com.xxx.bean.Rule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.utils.KieHelper;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class RuleEngineService {

    @Resource
    private KieContainer kieContainer;

    @Resource
    private RuleService ruleService;

    // 项目启动时自动加载已存在的规则
    @PostConstruct
    public void init() {
        reload();
    }

    public KieContainer getKieContainer() {
        return kieContainer;
    }

    public void reload() {
        System.out.println("reload rule...");

        // 借助 kieHelper 添加规则
        KieHelper kieHelper = new KieHelper();

        // 从数据库中获取所有的规则
        List<Rule> rules = ruleService.getRules();
        if (!CollectionUtils.isEmpty(rules)) {
            // 循环加载所有的规则
            for (Rule rule : rules) {
                String content = rule.getContent();
                kieHelper.addContent(content, ResourceType.DRL);
            }
        }

        // 校验规则是否异常
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.ERROR)) {
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ###");
        }

        // 重置容器
        kieContainer = kieHelper.getKieContainer();
    }
}

